﻿using BW.Mes.WinForms.Common;
using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static BW.Mes.WinForms.WareHouse.CreateStorageForm;

namespace BW.Mes.WinForms.WareHouse
{
    public partial class SuppliedMaterialsForm : DevExpress.XtraEditors.XtraForm
    {
        public SuppliedMaterialsForm()
        {
            InitializeComponent();
            IList<string> list = new List<string>();
            list.Add("采购");
            list.Add("客供料");
            comboBox1.DataSource = list;
            LoadSuppilerInput();
            LoadMaterial();
        }

        private void SuppliedMaterialsForm_Load(object sender, EventArgs e)
        {

        }




        /// <summary>
        /// 打印调用api
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void CreateSupp(object sender, EventArgs e)
        {
            var model = new SuppliedMaterialsInput
            {
               source= comboBox1.Text,
               deliveryNumber = deliveryNumber_textEdit.Text,
               externalName=textEdit3.Text,
               batchNumber=textEdit4.Text,
               productionTime=dateEdit1.DateTime,
               loseefficacyTime=dateEdit2.DateTime,
               eachNumber=int.Parse(textEdit5.Text),
              printNumber=int.Parse(textEdit6.Text),
              materialId=(long)gridLookUpEdit2.EditValue,
              suppilerid=(long)gridLookUpEdit3.EditValue,
              CreatedBy=RequestUser.InputUserName
            };
            // 调用 API 方法
            using (var client = new HttpClient())
            {
                //设置请求地址
                client.BaseAddress = new Uri("http://120.26.197.100:8022/");
                //创建JSON数据（转换数据类型）
                var json = JsonConvert.SerializeObject(model);
                //创建请求内容
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                //发送POST请求
                var response = await client.PostAsync("T3/SuppliedMaterials/CreateSuppliedMaterials", content);
                //判断是否成功
                if (response.IsSuccessStatusCode)
                {
                    XtraMessageBox.Show("打印成功");
                    this.DialogResult = DialogResult.OK;
                    deliveryNumber_textEdit.Text = "";
                    textEdit3.Text = "";
                    textEdit4.Text = "";
                    textEdit5.Text = "";
                    textEdit6.Text = "";
                    dateEdit1.Text = "";
                    dateEdit2.Text = "";
                    
                }
                else
                {
                    XtraMessageBox.Show("打印失败:" + response.ReasonPhrase);
                }
            }
        }


        /// <summary>
        /// 加载供应商信息
        /// </summary>
        private async void LoadSuppilerInput()
        {
            try
            {
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://120.26.197.100:8022/");
                    var response = await client.GetAsync("T2/Supplier/GetSupplier");

                    response.EnsureSuccessStatusCode();
                    var responseBody = await response.Content.ReadAsStringAsync();
                    var jsonObject = JsonConvert.DeserializeObject<dynamic>(responseBody);

                    if (jsonObject["pageDatas"] != null)
                    {
                        // 将pageDatas转换为WareHouseItem列表
                        var dataJson = jsonObject["pageDatas"].ToString();
                        var warehouses = JsonConvert.DeserializeObject<List<SuppilerInput>>(dataJson);

                        // 假设您改用了gridLookUpEdit1控件
                        gridLookUpEdit3.Properties.DataSource = warehouses;
                        gridLookUpEdit3.Properties.DisplayMember = "supplierName";
                        gridLookUpEdit3.Properties.ValueMember = "Id";

                        // 配置下拉框，只显示供应商名称
                        gridLookUpEdit3.Properties.View.Columns.Clear();
                        gridLookUpEdit3.Properties.View.Columns.Add(
                            new DevExpress.XtraGrid.Columns.GridColumn
                            {
                                FieldName = "supplierName",
                                Caption = "供应商名称",
                                Visible = true
                            }
                        );

                        // 设置默认提示文本
                        gridLookUpEdit3.Properties.NullText = "请选择供应商";
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载仓库数据失败: {ex.Message}", "错误");
            }
        }


        /// <summary>
        /// 加载物料信息
        /// </summary>
        private async void LoadMaterial()
        {
            try
            {
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://120.26.197.100:8022/");
                    var response = await client.GetAsync("T2/Product/GetProduct?PageIndex=1&PageSize=100");

                    response.EnsureSuccessStatusCode();
                    var responseBody = await response.Content.ReadAsStringAsync();
                    var jsonObject = JsonConvert.DeserializeObject<dynamic>(responseBody);

                    if (jsonObject["pageDatas"] != null)
                    {
                        // 将pageDatas转换为WareHouseItem列表
                        var dataJson = jsonObject["pageDatas"].ToString();
                        var warehouses = JsonConvert.DeserializeObject<List<Material>>(dataJson);

                        // 假设您改用了gridLookUpEdit1控件
                        gridLookUpEdit2.Properties.DataSource = warehouses;
                        gridLookUpEdit2.Properties.DisplayMember = "MaterialName";
                        gridLookUpEdit2.Properties.ValueMember = "Id";

                        // 配置下拉框，只显示供应商名称
                        gridLookUpEdit2.Properties.View.Columns.Clear();
                        gridLookUpEdit2.Properties.View.Columns.Add(
                            new DevExpress.XtraGrid.Columns.GridColumn
                            {
                                FieldName = "MaterialName",
                                Caption = "物料名称",
                                Visible = true
                            }
                        );

                        // 设置默认提示文本
                        gridLookUpEdit2.Properties.NullText = "请选择物料";
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载物料数据失败: {ex.Message}", "错误");
            }
        }





        /// <summary>
        /// 来料标签打印实体
        /// </summary>
        public class SuppliedMaterialsInput
        {
            public string source { get; set; }
            public string deliveryNumber { get; set; }
            public long suppilerid { get; set; }
            public string externalName { get; set; }
            public long materialId { get; set; }
            public string batchNumber { get; set; }
            public DateTime productionTime { get; set; }
            public DateTime loseefficacyTime { get; set; }
            public int eachNumber { get; set; }
            public int printNumber { get; set; }
            /// <summary>
            /// 创建人
            /// </summary>
            public string CreatedBy { get; set; }
        }

        /// <summary>
        /// 供应商
        /// </summary>
        public class SuppilerInput
        {
            public long Id { get; set; }
            public string supplierName { get; set; }
        }

        /// <summary>
        /// 物料
        /// </summary>
        public class Material
        {
            public long Id { get; set; }
            public string MaterialName { get; set; }
        }

        /// <summary>
        /// 打印按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            CreateSupp(sender,e);
        }
    }
}